<template>
<div class="units-and-price">
  <el-dialog class="unit-price-dialog" :title="$t('m.UnitsandPrice')" :visible.sync="dialogFormVisible" :modal="false" @close="newFloorFormClosed">
    <el-form :model="newFloorForm" :inline="true" ref="newFloorForm">
      <el-form-item :label="$t('m.Photo')" >
          <input type="file" name="photo" @change="getFilePhoto" style="display: none;"/>
          <div v-if="isShowAddPhoto" class="add-photo-box add-photo-box1">
            <a href="javascript:;" class="add-photos" @click='addPicPhoto'>
            <span class="glyphicon glyphicon-remove" >
              <i class="el-icon-plus"></i>
            </span>
            </a>
          </div>
          <div class="add-photo-box add-photo-box1" v-else>
            <img  :src="photoBlobUrl"  />
            <a href="javascript:;" @click='delImagePhoto()'>
            <span class="glyphicon glyphicon-remove">
              <i class="el-icon-delete"></i>
            </span>
            </a>
          </div>
      </el-form-item>
      <el-row :gutter="5">
        <el-col :span="8">
      <el-form-item  :label="$t('m.Description')"  prop="description">
        <el-input v-model="newFloorForm.description"></el-input>
      </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="5">
        <el-col :span="4">
          <el-form-item :label="$t('m.Floor')"  prop="floor">
          <el-select v-model="newFloorForm.floor" placeholder="" >
            <el-option v-for="c in floor" :key="c.value" :label="c.text" :value="c.value" ></el-option>
          </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item :label="$t('m.Widthft')" prop="width">
            <el-input type="number" v-model.number="newFloorForm.width"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item :label="$t('m.Lengthft')" prop="length">
            <el-input type="number" v-model.number="newFloorForm.length"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item :label="$t('m.Sizesqft')" prop="size">
            <el-input type="number" v-model.number="newFloorForm.size"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="5">
        <el-col :span="4">
          <el-form-item :label="$t('m.Master')" prop="master">
            <el-select v-model="newFloorForm.master" placeholder="">
              <el-option v-for="c in master" :key="c.value" :label="c.text" :value="c.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item :label="$t('m.Bedroom')" prop="bedroom">
            <el-select v-model="newFloorForm.bedroom" placeholder="">
              <el-option v-for="c in bedroom" :key="c.value" :label="c.text" :value="c.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item :label="$t('m.Bathroom')" prop="bathroom">
            <el-select v-model="newFloorForm.bathroom" placeholder="">
              <el-option v-for="c in bathroom" :key="c.value" :label="c.text" :value="c.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item :label="$t('m.Status')" prop="statusId">
            <el-select v-model="newFloorForm.statusId" placeholder="">
              <el-option v-for="c in status" :key="c.value" :label="c.text" :value="c.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="5">
        <el-col :span="4">
        <el-form-item :label="$t('m.Price1')" prop="price">
          <el-input type="number" v-model.number="newFloorForm.price"></el-input>
        </el-form-item>
      </el-col>
        <el-col :span="4">
          <el-form-item :label="$t('m.Option')" prop="option1">
            <el-select v-model="newFloorForm.option1" placeholder="">
              <el-option v-for="c in option1" :key="c.value" :label="c.text" :value="c.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item :label="$t('m.Price2')" prop="price2">
            <el-input type="number" v-model.number="newFloorForm.price2"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item :label="$t('m.Option')" prop="option2">
            <el-select v-model="newFloorForm.option2" placeholder="">
              <el-option v-for="c in option2" :key="c.value" :label="c.text" :value="c.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item :label="$t('m.Price3')" prop="price3">
            <el-input type="number" v-model.number="newFloorForm.price3"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item :label="$t('m.Option')" prop="option3">
            <el-select v-model="newFloorForm.option3" placeholder="">
              <el-option v-for="c in option3" :key="c.value" :label="c.text" :value="c.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">{{$t('m.Cancel')}}</el-button>
      <el-button type="primary" @click="addNewDevFloorInfo" v-if="editOrAdd">{{$t('m.AddNew')}}</el-button>
      <el-button type="primary" @click="editDevFloorInfo(addNewDevFloorInfos)" v-else>{{$t('m.Edit')}}</el-button>
    </div>
  </el-dialog>
  <!--<p>{{developmentsUnitsList}}</p>-->
  <el-table
    v-if="addNewDevFloorInfos.length>0"
    :data="addNewDevFloorInfos"
    stripe
    border
    header-row-class-name="floor-info-title"
    style="width: 100%">
    <el-table-column :label="$t('m.Operation')" min-width="160">
      <template slot-scope="scope">
        <el-row :gutter="5">
        <el-col :span="12">
        <el-button size="mini" width="40"  @click="handleEdit(scope.$index, addNewDevFloorInfos)">{{$t('m.Edit')}}</el-button>
        </el-col>
        <el-col :span="12">
          <el-button size="mini" width="40" type="danger" @click="handleDelete(scope.$index, addNewDevFloorInfos)">{{$t('m.Delete')}}</el-button>
        </el-col>
        </el-row>
      </template>
    </el-table-column>
    <el-table-column :label="$t('m.Photo')">
      <template slot-scope="scope">
       <img :src="scope.row.photoUrlView" alt="" :onerror="defaultImg"/>
      </template>
    </el-table-column>
    <el-table-column width="160" prop="description" :label="$t('m.Description')"></el-table-column>
    <el-table-column width="160" prop="floorName" :label="$t('m.Floor')"></el-table-column>
    <el-table-column width="100" prop="width" :label="$t('m.Widthft')"></el-table-column>
    <el-table-column width="100" prop="length" :label="$t('m.Lengthft')"></el-table-column>
    <el-table-column width="100" prop="size" :label="$t('m.Sizesqft')"></el-table-column>
    <el-table-column prop="master" :label="$t('m.Master')"></el-table-column>
    <el-table-column width="100" prop="bedroom" :label="$t('m.Bedroom')"></el-table-column>
    <el-table-column width="100" prop="bathroom" :label="$t('m.Bathroom')"></el-table-column>
    <el-table-column width="100" prop="statusId"  :label="$t('m.Status')"></el-table-column>
    <el-table-column prop="price" :label="$t('m.Price1')"></el-table-column>
    <el-table-column prop="option1" :label="$t('m.Option')"></el-table-column>
    <el-table-column prop="price2" :label="$t('m.Price2')"></el-table-column>
    <el-table-column prop="option2" :label="$t('m.Option')"></el-table-column>
    <el-table-column prop="price3" :label="$t('m.Price3')"></el-table-column>
    <el-table-column prop="option3" :label="$t('m.Option')"></el-table-column>
  </el-table>
</div>
</template>

<script>
  import floors from '@/json/floor'
  import mm_floors from '@/mmJson/floor'
  import masterBedroomBathroom from '@/json/master_bedroom_bathroom'
  import statusData from '@/json/UnitStatusData'
  export default {
    name: 'unitsAndPrice',
    props: [
      'developmentsUnitsList'
    ],
    data () {
      return {
        defaultImg: 'this.src="' + require('../../../static/default.png') + '"',
        // 編輯時記錄當前floor的index
        id: '',
        listIndex: '',
        developmentsId: '',
        dialogFormVisible: false,
        editOrAdd: true,
        floorTitle: 'Add New',
        editLocalStatus: false,
        // 单个photo上传预览url
        photoBlobUrl: '',
        // 单个photo上传blob对象
        blobsObjPhoto: '',
        master: masterBedroomBathroom,
        bedroom: masterBedroomBathroom,
        bathroom: masterBedroomBathroom,
        // floor: floors,
        // status: [
        //   {"text":"For sale","value":1},
        //   {"text":"Sold out","value":2}
        //   ],
        option1: [
          {'text': '1', 'value': 1},
          {'text': '2', 'value': 2},
          {'text': '3', 'value': 3}
        ],
        option2: [
          {'text': '1', 'value': 1},
          {'text': '2', 'value': 2},
          {'text': '3', 'value': 3}
        ],
        option3: [
          {'text': '1', 'value': 1},
          {'text': '2', 'value': 2},
          {'text': '3', 'value': 3}
        ],
        isShowAddPhoto: true,
        newFloorForm: {
          description: '',
          floor: null,
          width: null,
          length: null,
          size: null,
          master: 0,
          bedroom: 0,
          bathroom: 0,
          statusId: 1,
          price: null,
          price2: null,
          price3: null,
          option1: null,
          option2: null,
          option3: null
        },
        // 新增floor表单数据集合
        addNewDevFloorInfos: [],
        // 新增floor首步上传图片blob数据集合
        floorImgBlobs: []
      }
    },
    computed : {
      status(){
        if(this.$store.state.localLang == 'MM'){
          return  [
            {"text":"ေရာင္းရန္","value":1},
            {"text":"​ေရာင္​းၿပီး","value":2}
          ]
        }else {
          return  [
            {"text":"For sale","value":1},
            {"text":"Sold out","value":2}
          ]
        }
      },
      floor(){
        if(this.$store.state.localLang == 'MM'){
          return  mm_floors
        }else {
          return  floors
        }
      },
    },
    methods: {
      // 显示新增界面
      addPicPhoto (e) {
        e.preventDefault()
        document.getElementsByName('photo')[0].click()
        return false
      },
      // 获取图片文件
      getFilePhoto ($event) {
        let f = $event.target.files[0] || $event.dataTransfer.files[0]
          // 判断文件类型
        if (!f.type.match('image.*')) {
          this.$message.error('The type of photos mustbe image!')
          return false
        }
          // 读取图片base64数据并执行canvas压缩
        var reader = new FileReader()
        reader.onload = ((theFile) => {
          return (e) => {
            this.setImageCompressPhoto(e, theFile.name)
          }
        })(f)
        reader.readAsDataURL(f)
      },
      // 压缩图片
      setImageCompressPhoto (e, f) {
        let img = new Image()
        img.src = e.target.result
        let canvas = document.createElement('canvas')
        let context = canvas.getContext('2d')
        let self = this
        img.onload = function () {
          // 图片原始尺寸
          let originWidth = this.width
          var originHeight = this.height
          // 最大尺寸限制
          let maxWidth = 400
          let maxHeight = 400
          // 目标尺寸
          let targetWidth = originWidth
          let targetHeight = originHeight
          // 图片尺寸超过400x400的限制
          if (originWidth > maxWidth || originHeight > maxHeight) {
            if (originWidth / originHeight > maxWidth / maxHeight) {
              // 更宽，按照宽度限定尺寸
              targetWidth = maxWidth
              targetHeight = Math.round(maxWidth * (originHeight / originWidth))
            } else {
              targetHeight = maxHeight
              targetWidth = Math.round(maxHeight * (originWidth / originHeight))
            }
          }
          // canvas对图片进行缩放
          canvas.width = targetWidth
          canvas.height = targetHeight
          // 清除画布
          context.clearRect(0, 0, targetWidth, targetHeight)
          // 图片压缩
          context.drawImage(img, 0, 0, targetWidth, targetHeight)
          // canvas转为blob并上传
          canvas.toBlob((blob) => {
            console.log(blob)
            self.blobsObjPhoto = blob
            self.photoBlobUrl = URL.createObjectURL(blob)
            self.isShowAddPhoto = false
          }, 'image/png', 0.7)
        }
      },
      delImagePhoto (e) {
        if (!e) {
          /* 本地图片编辑改动一 */
          // URL.revokeObjectURL(this.photoBlobUrl)
        }
        this.photoBlobUrl = ''
        this.blobsObjPhoto = ''
        this.isShowAddPhoto = true
        document.getElementsByName('photo')[0].value = ''
        return false
      },
      addNewDevFloorInfo () {
        let floorName = ''
        for (var f of floors) {
          if (this.newFloorForm.floor === f.value) {
            floorName = f.text
            break
          }
        }
        let floorInfo = {
          // 列表图片预览，最后表单提交时清空
          photoUrlView: this.photoBlobUrl,
          photoUrl: '',
          description: this.newFloorForm.description,
          floor: this.newFloorForm.floor,
          width: this.newFloorForm.width,
          length: this.newFloorForm.length,
          size: this.newFloorForm.size,
          master: this.newFloorForm.master,
          bedroom: this.newFloorForm.bedroom,
          bathroom: this.newFloorForm.bathroom,
          statusId: this.newFloorForm.statusId,
          option1: this.newFloorForm.option1,
          option2: this.newFloorForm.option2,
          option3: this.newFloorForm.option3,
          price: this.newFloorForm.price,
          price2: this.newFloorForm.price2,
          price3: this.newFloorForm.price3,
          // 表单提交前先上传imgBlob
          imgBlob: this.blobsObjPhoto,
          floorName: floorName
        }
        // let imgblobs = {
        //  imgBlob: this.blobsObjPhoto
        // }
        // this.floorImgBlobs.push(imgblobs)
        this.addNewDevFloorInfos.push(floorInfo)
        // console.log(this.floorImgBlobs)
        console.log(this.addNewDevFloorInfos)
        // 重置新增floor的表单
        this.$refs['newFloorForm'].resetFields()
        this.dialogFormVisible = false
        this.delImagePhoto(true)
      },
      // 编辑楼层信息
      editDevFloorInfo (e) {
        this.developmentsId = this.$route.query.id || ''
        let floorName = ''
        for (var f of floors) {
          if (this.newFloorForm.floor === f.value) {
            floorName = f.text
            break
          }
        }
        let floorInfo = {
          // 編輯時傳入id
          id: this.id,
          developmentsId: this.developmentsId,
          floorTitle: '',
          // 列表图片预览，最后表单提交时清空
          photoUrlView: this.photoBlobUrl,
          photoUrl: this.photoBlobUrl,
          description: this.newFloorForm.description,
          floor: this.newFloorForm.floor,
          width: this.newFloorForm.width,
          length: this.newFloorForm.length,
          size: this.newFloorForm.size,
          master: this.newFloorForm.master,
          bedroom: this.newFloorForm.bedroom,
          bathroom: this.newFloorForm.bathroom,
          statusId: this.newFloorForm.statusId,
          option1: this.newFloorForm.option1,
          option2: this.newFloorForm.option2,
          option3: this.newFloorForm.option3,
          price: this.newFloorForm.price,
          price2: this.newFloorForm.price2,
          price3: this.newFloorForm.price3,
          // 表单提交前先上传imgBlob
          imgBlob: this.blobsObjPhoto,
          floorName: floorName
        }
        this.addNewDevFloorInfos.splice(this.listIndex, 1, floorInfo)
        console.log(this.floorInfo)
        console.log(this.addNewDevFloorInfos)
        // 重置新增floor的表单
        // this.$refs['newFloorForm'].resetFields()
        this.dialogFormVisible = false
        this.delImagePhoto(true)
        this.editLocalStatus = false
        this.newFloorForm = {
          description: '',
          floor: null,
          width: null,
          length: null,
          size: null,
          master: 0,
          bedroom: 0,
          bathroom: 0,
          statusId: 1,
          price: null,
          price2: null,
          price3: null,
          option1: null,
          option2: null,
          option3: null,
          floorName:''
        }
      },
      // message alert
      messageT (type, msg) {
        this.$message({
          showClose: true,
          message: msg,
          duration: 1500,
          type: type
        })
      },
      handleDelete (index, row) {
        // row.splice(index, 1)
        // this.floorImgBlobs.splice(index, 1)
        console.log(index, row)
        this.$confirm('Delete?')
          .then(_ => {
            row.splice(index, 1)
          })
          .catch(_ => {})
      },
      // 显示编辑界面
      handleEdit (index, row) {
        // this.newFloorForm = row[index]
        this.newFloorForm = {
          description: row[index].description,
          floor: row[index].floor,
          width: row[index].width,
          length: row[index].length,
          size: row[index].size,
          master: row[index].master,
          bedroom: row[index].bedroom,
          bathroom: row[index].bathroom,
          statusId: row[index].statusId,
          price: row[index].price,
          price2: row[index].price2,
          price3: row[index].price3,
          option1: row[index].option1,
          option2: row[index].option2,
          option3: row[index].option3
        }
        if (row[index].id) {
          this.photoBlobUrl = row[index].photoUrl
          this.id = row[index].id
        } else {
          this.photoBlobUrl = row[index].photoUrlView
          /* 本地图片编辑改动二 */
          this.blobsObjPhoto = row[index].imgBlob
          this.editLocalStatus = true
        }
        this.listIndex = index
        this.floorTitle = 'Edit Info'
        this.editOrAdd = false
        this.dialogFormVisible = true
        // 预览图片地址不为空时隐藏添加图片按钮，显示图片预览
        if (this.photoBlobUrl) {
          this.isShowAddPhoto = false
        }
      },
      newFloorFormClosed () {
        this.$refs['newFloorForm'].resetFields()
        if (!this.editLocalStatus) {
          this.delImagePhoto(true)
          this.editLocalStatus = false
        } else {
          this.photoBlobUrl = ''
          this.editLocalStatus = false
          this.isShowAddPhoto = true
        }
        // 编辑弹框弹出后，数组操作原因resetFields方法无效，手动置空表单
        this.newFloorForm = {
          description: '',
          floor: null,
          width: null,
          length: null,
          size: null,
          master: 0,
          bedroom: 0,
          bathroom: 0,
          statusId: 1,
          price: null,
          price2: null,
          price3: null,
          option1: null,
          option2: null,
          option3: null,
          floorName: ''
        }
        this.floorTitle = 'Add New'
        this.editOrAdd = true
        console.log(this.addNewDevFloorInfos)
      }
    }
  }
</script>
<style>
  .unit-price-dialog .el-dialog{
    min-width: 920px!important;
  }
  .add-photo-box {
    position: relative;
    width: 100%;
    height: 39px;
    margin-right:10px;
    overflow: hidden;
    border-radius: 4px;
    border: 1px solid #d8dce5;
  }
  .add-photo-box1{
    width: 77px;
    height: 77px;
    border: 1px dashed #D8DCE5;
    border-radius: 5px;
  }
  .add-photo-box a{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
  .add-photo-box img{
    width: 100%;
    height:100%;
    display: block;
  }
  .add-photo-box .glyphicon{
    height:39px;
    line-height:39px;
    width:100%;
  }
  .add-photo-box .add-photos .glyphicon {
    background: rgba(255,255,255,.7);
  }
  .add-photo-box1 .glyphicon{
    height:77px;
    line-height:77px;
    width:100%;
  }
  .units-and-price {
    border-top: 1px solid transparent;
  }
  .units-and-price .cell img{
    max-height:36px;
    max-width:60px;
  }
  .units-and-price .add-new{
    padding: 20px 0 20px 0;
    border-top: 1px solid #fff;
  }
  .units-and-price .el-input__suffix{
    top:0;
    height:100%;
  }
  .edit-del{
    display: flex;
  }
  .edit-del button{
    flex:1;
  }
  /*tr.floor-info-title{*/
    /*background:#f4f5f9 !important;*/
  /*}*/
</style>
